package com.mxf.miaosha.service;

import com.mxf.miaosha.VO.LoginVO;
import com.mxf.miaosha.dao.MiaoshaUserDao;
import com.mxf.miaosha.domain.MiaoshaUser;
import com.mxf.miaosha.exception.GlobalException;
import com.mxf.miaosha.redis.MiaoshaUserKey;
import com.mxf.miaosha.redis.RedisService;
import com.mxf.miaosha.result.CodeMsg;
import com.mxf.miaosha.result.Result;
import com.mxf.miaosha.util.MD5Util;
import com.mxf.miaosha.util.UUIDUtil;
import com.sun.org.apache.bcel.internal.classfile.Code;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class MiaoshaUserService {

    public static final String COOKIE_NAME_TOKEN = "token";

    @Autowired
    private MiaoshaUserDao miaoshaUserDao;

    @Autowired
    private RedisService redisService;

    /**
     * 获取对象，使用对象缓存
     * @param id
     * @return
     */
    public MiaoshaUser getById(long id) {
        MiaoshaUser user = redisService.get(MiaoshaUserKey.getById, "" + id, MiaoshaUser.class);
        if(user != null) {
            return user;
        }
        user = miaoshaUserDao.getById(id);
        if(user != null) {
            redisService.set(MiaoshaUserKey.getById, "" + id, user);
        }
        return user;
    }

    /**
     * 更新对象
     * @param token
     * @param id
     * @param passwordNew
     * @return
     */
    public boolean updatePassword(String token, long id, String passwordNew) {
        // 获取对象
        MiaoshaUser user = getById(id);
        if(user == null) {
            throw new GlobalException(CodeMsg.MOBILE_EMPTY);
        }
        // 更新数据库
        MiaoshaUser miaoshaUser = new MiaoshaUser();
        miaoshaUser.setId(id);
        miaoshaUser.setPassword(MD5Util.formPassToDBPass(passwordNew, user.getSalt()));
        miaoshaUserDao.updatePassword(miaoshaUser);

        // 更新缓存 , token , 和对象缓存都要更新
        redisService.delete(MiaoshaUserKey.getById, "" + id);
        user.setPassword(miaoshaUser.getPassword());
        redisService.set(MiaoshaUserKey.getById, "" + id, user);

        // 更新token， token不能删除否则无法登陆
        redisService.set(MiaoshaUserKey.token, token, user);
        return true;
    }

    /**
     * 从获取token
     * @param response
     * @param token
     * @return
     */
    public MiaoshaUser getByToken(HttpServletResponse response, String token) {
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        MiaoshaUser user = redisService.get(MiaoshaUserKey.token, token, MiaoshaUser.class);
        //延长有效期
        if(user != null) {
            addCookie(response, token, user);
        }
        return user;
    }

    /**
     * 登录
     * @param loginVO
     * @return
     */
    public boolean login(HttpServletResponse response, LoginVO loginVO) {
        if(loginVO == null) {
            throw new GlobalException(CodeMsg.SERVER_ERROR);
        }
        String mobile = loginVO.getMobile();
        String formpass = loginVO.getPassword();

        MiaoshaUser user = getById(Long.parseLong(mobile));
        // 验证手机号是否存在
        if(user == null) {
            throw new GlobalException(CodeMsg.MOBILE_NOT_EXIST);
        }

        // 验证密码
        String dbPass = user.getPassword();
        String dbSalt = user.getSalt();

        String calcPass = MD5Util.formPassToDBPass(formpass, dbSalt);
        if(!dbPass.equals(calcPass)) {
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }

        //生成cookie
        String token = UUIDUtil.uuid();
        addCookie(response, token, user);

        return true;
    }

    private void addCookie(HttpServletResponse response, String token, MiaoshaUser user) {
        redisService.set(MiaoshaUserKey.token, token, user);
        Cookie cookie = new Cookie(COOKIE_NAME_TOKEN, token);
        cookie.setMaxAge(MiaoshaUserKey.TOKEN_EXPIRE);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
